import {messages} from "share/common";
/**
 * Created by 13576 on 2017/10/6.
 */
import React from 'react'
import {connect} from 'react-redux'

import {Button, Col, Row, Select, Form, Input, message, Card,Affix} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;

import Chooser from  'components/chooser';
import UploadFile from 'components/upload'
import httpFetch from 'share/httpFetch';
import config from 'config'
import menuRoute from 'routes/menuRoute'
import IeFileUpload from 'components/template/ie-file-upload/ie-file-upload'
import Condition from 'components/condition'
const { If, Else } = Condition;
import budgetJournalService from 'containers/budget/budget-journal/budget-journal.service'
import "styles/budget/budget-journal/new-budget-journal.scss"

class NewBudgetJournalFrom extends React.Component {
  // GENERATE(1001)//编辑中
  // , APPROVAL(1002)//审批中
  // , WITHDRAW(1003) // 撤回
  // , APPROVAL_PASS(1004) // 审批通过
  // , APPROVAL_REJECT(1005) // 审批驳回
  // , DELETE(1006) //已删除
  // //对公报销单 2001
  // //预付款申请单 3001
  // //付款申请单 4001
  // //预算日记账 5001
  // ,POSTED(5001)//复核(过账)
  // ,BACKLASH_SUBMIT(5002)//:反冲提交
  // ,BACKLASH_CHECKED(5003)//:反冲审核
  // //合同  6001
  // ,HOLD(6001)//暂挂中
  // ,CANCEL(6002)//已取消
  // ,FINISH(6003)//已完成

  // // 记录操作历史加的
  // ,NOT_HOLD(6004) //取消暂挂
  constructor(props) {
    super(props);
    this.state = {
      loading:false,
      budgetJournalDetailPage: menuRoute.getRouteItem('budget-journal-detail', 'key'),    //预算日记账详情
      budgetJournalPage: menuRoute.getRouteItem('budget-journal', 'key'),    //预算日记账
      idSelectJournal: false,
      isStructureIn: false,
      defaultValueList:{},
      defaultDataList:[
        {type:'chooser',event:'versionName',defaultValueKey:'versionName',
          url:`${config.budgetUrl}/api/budget/versions/query?isEnabled=true&status=CURRENT&organizationId=${props.organization.id}`},
        {type:'chooser',event:'scenarioName',defaultValueKey:'scenarioName',
          url:`${config.budgetUrl}/api/budget/scenarios/query?defaultFlag=true&organizationId=${props.organization.id}`}
      ],
      structureGroup: [],
      periodStrategy: [],
      periodPeriodQuarter: [],
      periodPeriod: [],
      structureFlag: true,
      periodFlag: true,
      periodYearFlag: true,
      periodQuarterFlag: true,
      periodStrategyFlag: true,
      journalTypeIdFlag:true,
      attachmentOID: [],
      formOid:null,
      documentOid:null
    };
  }



  componentWillMount() {
    this.getPeriodStrategy();
    this.getDefaultValue();
  }

  //获取表单默认值
  getDefaultValue(){
    let defaultValueList =  this.state.defaultValueList;
    let defaultDataList = this.state.defaultDataList;
    defaultDataList.map((item)=>{
      httpFetch.get(item.url).then((response)=>{
        if(item.type === "chooser"){
          defaultValueList[item.defaultValueKey]=response.data;
            this.props.form.setFieldsValue(
            defaultValueList
          )
        }
      }).catch((e)=>{
          if(e.response)
            message.error(e.response.data.message)
      })
    })
  }


  //获取编制期段
  getPeriodStrategy = () => {
    this.getSystemValueList(2002).then((response) => {
      let periodStrategy = [];
      response.data.values.map((item) => {
        let option = {
          key: item.code,
          label: item.messageKey
        };
        periodStrategy.push(option);
      });
      this.setState({
        periodStrategy: periodStrategy,
      })
    });
  };


  //保存日记账头
  saveHeard = (value) => {
    this.setState({
      loading:true,
    })
    budgetJournalService.addBudgetJournalHeaderLine(value).then((response) => {
      let path = this.state.budgetJournalDetailPage.url.replace(":journalCode", response.data.dto.id);
      this.context.router.push(path);
      this.setState({
        loading:false,
      })
    }).catch(e => {
      message.error(e.response.data.message)
      this.setState({
        loading:false,
      })
    })
  };


  //处理表单数据
  handleFrom = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        let userData = {
          "dto": {
             "companyId": this.props.company.id,
             "companyName": this.props.company.name,
             "organizationId": this.props.organization.id,
             "organizationName": this.props.organization.organizationName,
             "structureId": value.structureId,
             "structureName": "structureName",
             "description": value.description,
             "reversedFlag": "N",
             "sourceBudgetHeaderId": undefined,
             "sourceType": undefined,
             "employeeId": this.props.user.id,
             "employeeName": this.props.user.fullName,
             "unitName": "periodNumber",
             'versionId': value.versionName[0].id,
             'versionName': value.versionName[0].versionName,
             'scenarioId': value.scenarioName[0].id,
             'scenarioName': value.scenarioName[0].scenarioName,
             "status": "NEW",
             "journalTypeId": value.journalTypeName[0].id,
             "journalTypeName": value.journalTypeName[0].journalTypeName,
             "periodStrategy": value.periodStrategy,
             "versionNumber": "1",
             "attachmentOID": this.state.attachmentOID,
             "formOid":this.state.formOid,
             "documentType":this.state.documentOid
          }
          ,
          "list": []
        };
        this.saveHeard(userData);
      }
    })
  };


  //根据预算日记账类型，获得预算表
  getStructure(value) {
    let params = {};
    params.companyId = this.props.company.id;
    params.journalTypeId = value;

    budgetJournalService.getStructureByBudgetJournalType(params).then(res => {

      let structureId = null;
      let queryDefaultStructureParams = {};
      queryDefaultStructureParams.journalTypeId = value;
      budgetJournalService.getDefaultStructure(queryDefaultStructureParams).then(response => {

        if (response.data) {

          res.data.map((item) => {
            item.key = item.id;
            if(item.key == response.data.id) {
              structureId = response.data.id;
            }
          })

          this.props.form.setFieldsValue({
            "structureId": structureId,
            "periodStrategy": response.data.periodStrategy
          })

        } else {
          res.data.map((item) => {
            item.key = item.id;
          })
        }
        this.setState({ "structureGroup": res.data });
      }).catch(e => { message.error(e.response.data.message) })

    }).catch(e => { message.error(e.response.data.message) })

    this.getFormOid(value);
  }



  getFormOid(value){
    let formOid =null;
    let documentOid =null;
    let params={};
    params.organizationId = this.props.organization.id;
    params.journalTypeId =value;
    params.page = 0;
    params.size = 50;
    budgetJournalService.getJournalType(params).then((res)=>{
      res.data.map((item)=>{
        if(item.id == value){
          formOid = item.form0id;
          documentOid = item.formType;
          this.setState({
            formOid,
            documentOid
          },()=>{})
        }
      })
    })
  }


  //选择预算表时，获得期间段
  handleSelectChange = (values) => {
    this.state.structureGroup.map((item) => {
      if (item.id == values) {
        const periodStrategy = item.periodStrategy;
        this.props.form.setFieldsValue({
          periodStrategy: periodStrategy,
        });
      }
    });

  };

  //取消
  HandleClear = () => {
    let path = this.state.budgetJournalPage.url;
    this.context.router.push(path);
  };


  //选择预算日记账类型，设置对应的预算表选
  handleJournalType = (value) => {
    if (value.length > 0) {
     let valueData = value[0];
      this.setState({
        idSelectJournal: true,
        structureFlag: false
      });
      this.props.form.setFieldsValue({
        structureId: ''
      });

      this.getStructure(valueData.id);
    }

  };

  //上传附件，获取OID
  handleFileUpload = (value) => {
    if (window.ISIE9) {
      let attachmentOID = [];
      value.map(item => attachmentOID.push(item.attachmentOID));
      this.setState({ attachmentOID })
    } else {
      this.setState({ attachmentOID: value })
    }
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const organization = this.props.organization;
    const {structureGroup, periodStrategy, structureFlag, periodStrategyFlag, loading} = this.state;
    const formItemLayout = {};
    const strategyOptions = structureGroup.map((item) => <Option key={item.id} value={String(item.id)}>{item.structureName}</Option>);
    const periodStrategyOptions = periodStrategy.map((item) => <Option key={item.key} value={item.key}>{item.label}</Option>);

    return (
      <div className="new-budget-journal">
        <div className="budget-journal-title">
          <div><h1>{messages('budget.key123'/*预算日记账*/)}</h1></div>
          <div className="budgetJournal-journal-title-detail">{messages('budget.key126'/*用于预算录入，提交审批*/)}</div>
        </div>
        <div className="divider"> </div>
        <Form onSubmit={this.handleFrom} style={{}}>
          <Card title={messages('budget.key100'/*基本信息*/)}  style={{with: "100%"}}>
            <Row gutter={40}>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key102'/*预算日记账编号*/)}>
                  {getFieldDecorator('journalCode', {
                    rules: [{}],
                    initialValue: '-'
                  })(
                    <Input disabled={true}/>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key103'/*申请人*/)}>
                  {getFieldDecorator('employeeId', {
                    rules: [{
                      required: true,
                      message: '',
                    }],
                    initialValue: this.props.user.fullName
                  })(
                    <Input disabled={true}/>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key127'/*预算组织*/)}>
                  {getFieldDecorator('organizationName', {
                    rules: [{
                      required: true,
                      message: '',
                    }],
                    initialValue: organization.organizationName
                  })(
                    <Input disabled={true}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={40}>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key85'/*公司*/)}>
                  {getFieldDecorator('companyId',{
                    rules: [{
                      required: true,
                      message: messages('common.can.not.be.empty', {name:"journalTypeName"}),
                    }],
                    initialValue: this.props.company.name
                  })(
                    <Input disabled={true}/>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key86'/*部门*/)}>
                  {getFieldDecorator('departmentName',{
                    rules: [{
                      required: true,
                      message: '',
                    }],
                    initialValue: this.props.user.departmentName
                  })(
                    <Input disabled={true}/>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
                  {getFieldDecorator('description', {
                    rules: [{
                      required: false,
                      max: 200,
                      message: messages('common.max.characters.length', {max: 200})
                    }],
                    initialValue: ''
                  })(
                    <Input disabled={false}/>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Card>
          <div className="divider"> </div>

          <Card title={messages('budget.key128'/*预算信息*/)}  style={{with: "100%"}}>
            <Row gutter={40}>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key105'/*预算日记账类型*/)}>
                  {getFieldDecorator('journalTypeName', {
                    rules: [{
                      required: true,
                      message: messages('common.can.not.be.empty', {name:messages('budget.key105'/*预算日记账类型*/)})
                    }]
                  })(
                    <Chooser
                      type='budget_journal_type'
                      labelKey='journalTypeName'
                      valueKey='id'
                      single={true}
                      listExtraParams={{"organizationId": this.props.organization.id}}
                      onChange={this.handleJournalType}
                    />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key106'/*预算表*/)}
                >
                  {getFieldDecorator('structureId', {
                    rules: [{
                      required: true,
                      message: messages('common.can.not.be.empty', {name:messages('budget.key106'/*预算表*/)})
                    }],

                  })(
                    <Select onSelect={this.handleSelectChange} disabled={structureFlag}>
                      {strategyOptions}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key109'/*编制期段*/)}>
                  {getFieldDecorator('periodStrategy', {
                    rules: [{
                      required: true,
                      message: messages('common.can.not.be.empty', {name:messages('budget.key109'/*编制期段*/)})
                    }],

                  })(
                    <Select disabled={periodStrategyFlag}>
                      {periodStrategyOptions}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={40}>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key108'/*版本*/)}>
                  {getFieldDecorator('versionName', {
                    rules: [{
                      required:true,
                      message: messages('common.can.not.be.empty', {name:messages('budget.key108'/*版本*/)})
                    }],
                    valuePropName:"value",
                    initialValue:this.state.defaultValueList["versionName"],
                  })(
                    <Chooser
                      type='budget_versions'
                      labelKey='versionName'
                      valueKey='id'
                      single={true}
                      listExtraParams={{"organizationId": this.props.organization.id,"isEnabled":true}}
                    />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('budget.key113'/*预算场景*/)}>
                  {getFieldDecorator('scenarioName', {
                    rules: [{
                      required:true,
                      message: messages('common.can.not.be.empty', {name:messages('budget.key113'/*预算场景*/)})
                    }],
                    valuePropsName:"value",
                    initialValue:this.state.defaultValueList["scenarioName"],
                  })(
                    <Chooser
                      type='budget_scenarios'
                      labelKey='scenarioName'
                      valueKey='id'
                      single={true}
                      listExtraParams={{"organizationId": this.props.organization.id,"isEnabled":true}}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
          </Card>

          <div className="divider" style={{height:16}}> </div>
          <Card title={messages('budget.key129'/*附件信息*/)} style={{with: "100%"}}>
            <Condition>
              <If value={window.ISIE9}>
                <IeFileUpload attachmentType="BUDGET_JOURNAL"
                              fileSize={10}
                              maxNum={9}
                              showMaxNum
                              token={this.props.authToken.access_token}
                              onChange={this.handleFileUpload}
                />
              </If>
              <Else>
                <Row>
                  <Col span={8}>
                    <UploadFile attachmentType="BUDGET_JOURNAL"
                                fileNum={9}
                                uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                                uploadHandle={this.handleFileUpload}
                    />
                  </Col>
                </Row>
              </Else>
            </Condition>
          </Card>
          <div className="divider" style={{height:40}}> </div>
          <Affix offsetBottom={0} className="bottom-bar">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('budget.key130'/*下一步*/)}</Button>
            <Button onClick={this.HandleClear} className="button-back">{messages('budget.key111'/*返回*/)}</Button>
          </Affix>
        </Form>
      </div>
    )
  }
}


NewBudgetJournalFrom.contextTypes = {
  router: React.PropTypes.object
};


const NewBudgetJournal = Form.create()(NewBudgetJournalFrom);

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    organization: state.login.organization,
    authToken: state.main.authToken
  }

}

export default connect(mapStateToProps)(NewBudgetJournal);
